package top.hserver.gateway.service.impl;

import top.hserver.core.ioc.annotation.Autowired;
import top.hserver.core.ioc.annotation.Bean;
import top.hserver.gateway.config.StrategyType;
import top.hserver.gateway.core.node.Manager;
import top.hserver.gateway.core.strategy.ServerNode;
import top.hserver.gateway.dto.GatewayRouterNodeDTO;
import top.hserver.gateway.service.GatewayRouterService;
import top.hserver.gateway.service.ServerService;

import java.net.InetSocketAddress;
import java.util.List;

/**
 * @author hxm
 */
@Bean
public class ServerServiceImpl implements ServerService {

    @Autowired
    private Manager manager;

    @Autowired
    private GatewayRouterService gatewayRouterService;


    @Override
    public void initServerData() {
        List<GatewayRouterNodeDTO> all = gatewayRouterService.all();
        for (GatewayRouterNodeDTO node : all) {
            try {
                ServerNode serverNode = new ServerNode();
                //连接数
                serverNode.setConnectNum(0L);
                //url
                serverNode.setUrl(node.getUrl());
                //路由ID
                serverNode.setRouterId(node.getRouterId());
                //匹配规则URl
                serverNode.setNodeId(node.getNodeId());
                //节点类型
                serverNode.setType(node.getType());
                //ip port
                InetSocketAddress inetSocketAddress = new InetSocketAddress(node.getIp(), node.getPort());
                serverNode.setInetSocketAddress(inetSocketAddress);
                try {
                    if (inetSocketAddress.getAddress().isReachable(1000)) {
                        //健康状态
                        serverNode.setHealth(true);
                    } else {
                        //健康状态
                        serverNode.setHealth(false);
                    }
                } catch (Exception e) {
                    serverNode.setHealth(false);
                }
                //节点名字
                serverNode.setNodeDesc(node.getNodeDesc());
                //路由名字
                serverNode.setRouterDesc(node.getRouterDesc());
                //负载类型
                serverNode.setStrategyType(StrategyType.values()[node.getStrategyType()-1]);
                manager.addServerNode(node.getRouterId(), serverNode);
            }catch (Exception e){
                e.printStackTrace();
            }
        }

    }

    @Override
    public void restartServerData() {
        manager.clearAll();
        initServerData();
    }
}
